import IconArrowLeft from "@/assets/svg/icon-arrow-left"
import IconArrowRight from "@/assets/svg/icon-arrow-right"
import React, { memo, useEffect, useRef, useState } from "react"
import { ViewWrapper } from "./style"

const ScrollView = memo((props) => {
  // 定义内部状态
  const [showRight, setShowRight] = useState(false)
  const [showLeft, setShowLeft] = useState(false)
  const [posIndex, setPosIndex] = useState(0)
  // 用来记录这个值 如果直接定义 会造成值的重复刷新
  const totalDistanceRef = useRef()

  // 组件渲染完毕后，判断是否显示右侧按钮
  const scrollContentRef = useRef()
  useEffect(() => {
    const scrollWidth = scrollContentRef.current.scrollWidth
    const clientWidth = scrollContentRef.current.clientWidth
    const totalDistance = scrollWidth - clientWidth
    setShowRight(totalDistance > 0)
    totalDistanceRef.current = totalDistance
  }, [props.children])

  // 事件处理函数
  function handleControlBtn(isRight) {
    const newIndex = isRight ? posIndex + 1 : posIndex - 1
    const newEl = scrollContentRef.current.children[newIndex]
    // 注意获取 offsetWidth 时，父级元素要加定位
    const newOffsetWidth = newEl.offsetLeft
    scrollContentRef.current.style.transform = `translate(-${newOffsetWidth}px)`
    setPosIndex(newIndex)
    // 是否继续显示右侧按钮
    setShowRight(totalDistanceRef.current > newOffsetWidth)
    // 是否显示左侧按钮
    setShowLeft(newOffsetWidth > 0)
  }

  return (
    <ViewWrapper>
      {showLeft && (
        <div className="control left" onClick={(e) => handleControlBtn(false)}>
          <IconArrowLeft />
        </div>
      )}
      {showRight && (
        <div className="control right" onClick={(e) => handleControlBtn(true)}>
          <IconArrowRight />
        </div>
      )}
      <div className="scroll">
        <div className="scroll-content" ref={scrollContentRef}>
          {/* 插槽作用 */}
          {props.children}
        </div>
      </div>
    </ViewWrapper>
  )
})

export default ScrollView
